使用標準資料庫裡的 net/http
Golang 的 net/http 提供了建立和管理 HTTP 服務器 和 客戶端 的功能。
要使用 net/http 包建立 HTTP 服務器,可以使用 http.ListenAndServe() 。
package main
import (
"fmt"
"net/http"
)
func main() {
// 建立一個 HTTP 服務器
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
http.ListenAndServe(":8080", nil)
}
這個程式碼會建立一個簡單的 http 服務器,當用戶訪問 http://localhost:8080 時,會回傳一個 "Hello, World!" 的 response。
要使用 net/http 建立 HTTP 客戶端,可以使用 http.Get()、http.Post() 等函數。
package main
import (
"fmt"
"net/http"
)
func main() {
// 建立一個 HTTP 客戶端
resp, err := http.Get("http://localhost:8080")
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
// 讀取響應
fmt.Println(resp.StatusCode)
fmt.Println(resp.Header)
fmt.Println(ioutil.ReadAll(resp.Body))
}
這個程式碼會建立一個 HTTP 客戶端,並向 http://localhost:8080 發送一個 GET 請求。
HandleFunc 是一個接受 http.ResponseWriter 和 *http.Request 作為參數的函數,用於處理 HTTP。
http.HandleFunc("/hello",
func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
Framework 是一種用於開發 Web應用程式 的軟體框架,提供一組 預先定義 的 工具 、 函數 、 類別 和 模式 ,用於 簡化 和 加速 Web應用程式的 開發過程。
一些 golang framework :
Gin :是一個 輕量級 且 高性能 的 Web 框架,具有 快速 的 路由引擎 和 中間件 支援。適合構建 RESTful API 和 Web 應用程式。
GitHub:https://github.com/gin-gonic/gin
Echo:也是輕量級的 Web 框架,專注於高性能和開發速度。它具有 簡單的 API 和 內建的中間件,使其易於入門和使用。
GitHub:https://github.com/labstack/echo
Fiber:比較新興,主要用於提供高性能和 低內存占用。有 快速 的 路由引擎、 中間件 支援以及 異步請求處理 。
GitHub:https://github.com/gofiber/fiber
Chi:可以與 標準庫 的 net/http 一起使用,而不是一個完整的框架。它適用於需要 自定義路由 的情況。
GitHub:https://github.com/go-chi/chi
今天簡單介紹web,接下來幾天會帶一點標準庫。